from mininet.node import Docker
from docker import client
import os

class Container(Docker):
    def __init__(self, name, dimage=None, dcmd=None, build_params={},
                 **kwargs) -> None:
        self.ready = False
        self.dclient = client.from_env()
        super().__init__(name, dimage, dcmd, build_params, **kwargs)
        
    def cmd(self, *args, **kwargs):
        print(args)
        if not self.ready and ('ip' in args or 'ifconfig' in args):
            info = self.dclient.api.inspect_container(self.dc)
            self.nspid = info['State']['Pid']
            return self._nsenter_run(self.nspid, ' '.join(args))
        return super().cmd(*args, **kwargs)

    def _nsenter_run(self, pid, cmd):
        # c = 'nsenter -t ' + str(pid) + ' -n -m -p ' + cmd
        c = 'nsenter -t ' + str(pid) + ' -n ' + cmd
        output = os.popen(c)
        return output.read()